<?php
namespace app\api\controller;
use think\Request;
use think\Db;
use think\Controller;
use think\Session;
use changpay\ChangPay;
use app\api\controller\Order;
use app\common\controller\order\Orderget;
use app\common\controller\chuanglan\ChuanglanSmsApi as CLApi;
use app\common\controller\system\Docking;
use app\admin\controller\system\SmsTemplate;
use app\api\controller\lishidai\Songsong;
class Notify extends Controller {
	//前台用户支付 回调  续期  获取 还款
	public function changjie_bank() {
		$data = $this -> request -> param(true);
				$data_huankuan=json_encode($data,TRUE);
				$fp = fopen('./payment/huankuan_xuqi.txt',"a+");
				$time=date('Y-m-d H:i:s');
		        fwrite($fp,$time."\n");
				fwrite($fp,$data_huankuan."\n");
		        fclose($fp); 
//		p($data);die;
		if ($data['trade_status'] == 'TRADE_SUCCESS') {
			$outer = $data['outer_trade_no'];
			$flag = explode("/", $outer);
			$type = $flag[2];
			//还款类型 1 还款 2续期
			$orderSn = $flag[1];
			//订单号
		
			if ($type == '1') {
				// 启动事务
				Db::startTrans();
				try {
					$loans_applylist_re = Db::table('xb_loans_applylist') -> where('OrderSn', $orderSn) -> find();
					//订单全部数据
					//		更改订单表   状态 LoanStatus
					$loans_applylist['LoanStatus'] = '3';
					//已经完成
					$loans_applylist['SjFkTime'] = date('Y-m-d H:i:s');
					//实际还款时间
					$loans_applylist_re_cd = Db::table('xb_loans_applylist') -> where('OrderSn', $orderSn) -> update($loans_applylist);
					//      写入支付记录表
					$Orer = new Order();
					$money = $Orer -> getOrderShould($loans_applylist_re);
					$loans_paylist=[
					'OrderSn' =>  $loans_applylist_re['OrderSn'],//订单号吗
					'CreateTime' =>  date('Y-m-d H:i:s'),//时间
					'Type' =>  '4',//还款类型 1部分还款 2结清 3豁免 4线上还款 5线上展期 6线下还款 7线下展期  
					'pay' =>  '6',//还款方式 1线下微信 2线下支付宝 3线下银联 4线上微信 5线上支付宝 6线上银联 7豁免
					'UserID' =>  $loans_applylist_re['UserID'],//用户ID
					'AppID' =>  $loans_applylist_re['ID'],//订单ID
					'OrderAmount' => $money,//实际还款金额
					'TradeNo' =>  $data['inner_trade_no'], //流水
					];
					$loans_paylist_re = Db::table('xb_loans_paylist') -> insertGetId($loans_paylist);
					//			        p($loans_paylist_re);die;
					//			写入还款记录表
					$loans_hklist=[
					'OrderSn'     =>   $loans_applylist_re['OrderSn'],//订单号
					'TotalMoney'  =>   $money,  //实际还款金额
					'ApplyID'     =>   $loans_applylist_re['ID'],
					'OrderSn'     =>   $loans_applylist_re['OrderSn'],
					'HkTime'      =>   date('Y-m-d H:i:s'),//还款时间
					'Type'        =>   '4',//还款类型 1部分还款 2结清 3豁免 4线上还款 5线上展期 6线下还款 7线下展期  
					'pay'         =>   '6',//还款方式 1线下微信 2线下支付宝 3线下银联 4线上微信 5线上支付宝 6线上银联 7豁免
					'UserID'      =>   $loans_applylist_re['UserID'],
					'TradeNo'     =>   $data['inner_trade_no'], //流水
					];
					$loans_hklist_re = Db::table('xb_loans_hklist') -> insertGetId($loans_hklist);
					Db::commit();
					echo 'success';
//					给利时代回调 还款状态
                    $aaa=[
					'order_sn'=>$loans_applylist_re['OrderSn'],
					'repay_result'=>'200',
					'fail_reason'=>'',
					];
		            $songsong=new Songsong();
					$re_huankuan=$songsong->repayStatusFeedback($aaa);//还款结果回调接口
					Db::table('xb_loans_applylist') -> where(['OrderSn'=>$loans_applylist_re['OrderSn']]) -> update(['lishidai_huankuan'=>$re_huankuan]);
					$smsTemp = (new SmsTemplate())->getSmsInfo('repayment_Inform');
					$userInfo = db('loans_applylist')->alias('a')
	                  ->where('a.ID',$loans_applylist_re['ID'])
	                  ->join('xb_mem_info m','a.UserID = m.ID')
	                  ->find();
	                $bankInfo = db('renzen_bank')->where(['UserID' => $loans_applylist_re['UserID']])->find();
				    $smsTempStr = str_replace(['#name#','#money#'],[$userInfo['TrueName'],$money],$smsTemp['Content']);
				    $result1 = (new CLApi())->sendSMS($userInfo['Mobile'],$smsTempStr);
				    $result2 = json_decode($result1,true);
			        //写入对接产品记录表
			        (new Docking())->addDocking(1,($result2['code'] == 0)?2:3,'chuanglan','畅捷主动还款回调',$result1);
					
				} catch (\Exception $e) {
					// 回滚事务
					Db::rollback();
				}

			} else {
				// 启动事务
				Db::startTrans();
				try {
					$LoanStatus = Db::table('xb_loans_applylist') -> where('OrderSn', $orderSn) -> find();
//					p($LoanStatus);die;
                    //		更改订单表 is_fujie  字段   xjnums 字段加1
					$UserID = $LoanStatus['UserID'];
					
					$Orderget=New Orderget();
		            $get_days_fakuan=$Orderget ->get_days_fakuan(strtotime(date("Y-m-d"),time()),strtotime($LoanStatus['YyFkTime']),$LoanStatus);
					if($get_days_fakuan['datas']=='0'){
						$app_type='3';
					}else{
						$app_type='4';
					}
                    $ApplyDay=$LoanStatus['ApplyDay'];
					$ApplyDay=$ApplyDay-1;
					$YyFkTime=$Orderget->get_time($LoanStatus['YyFkTime'],$ApplyDay);
					
					$loans_applylist=[
					'is_fujie'   =>  '1',//复借
					'xjnums'     =>  $LoanStatus['xjnums'] + 1,//复借次数
					'YyFkTime'   =>  $YyFkTime,//预约还款时间
					'app_type'   => $app_type,//订单类型 
					];
//					
//					p($loans_applylist);die;
					$loans_applylist_re = Db::table('xb_loans_applylist') -> where('ID', $LoanStatus['ID']) -> update($loans_applylist);
					//写入展期表  订单号为 唯一连接条件
					$loans_xjapplylist=[
					'OrderSn'   =>   $LoanStatus['OrderSn'],//订单号码
					'TotalMoney'   =>   $LoanStatus['zhanqifei'],//展期费
					'LoanDay'   =>  $LoanStatus['ApplyDay'],//展期天数
					'Type' =>  '5',//还款类型 1部分还款 2结清 3豁免 4线上还款 5线上展期 6线下还款 7线下展期  
					'pay' =>  '6',//还款方式 1线下微信 2线下支付宝 3线下银联 4线上微信 5线上支付宝 6线上银联 7豁免
					'PayTime'   =>   date('Y-m-d H:i:s'),
					'CreateTime'   =>   date('Y-m-d H:i:s'),
					'UserID'   =>  $UserID,//用户ID
					'AppID'   =>   $LoanStatus['ID'],//订单ID
					'YyFkTime'   =>   $YyFkTime,//预约还款时间
					 'TradeNo'         => $data['inner_trade_no'], //流水
					];
					$loans_xjapplylist_re = Db::table('xb_loans_xjapplylist') -> insertGetId($loans_xjapplylist);
				
					//					p($loans_xjapplylist_re);die;
					//      写入支付记录表
					$loans_paylist=[
					'OrderSn' =>  $LoanStatus['OrderSn'],//订单号吗
					'CreateTime' =>  date('Y-m-d H:i:s'),//订单号吗
					'Type' =>  '5',//还款类型 1部分还款 2结清 3豁免 4线上还款 5线上展期 6线下还款 7线下展期  
					'pay' =>  '6',//还款方式 1线下微信 2线下支付宝 3线下银联 4线上微信 5线上支付宝 6线上银联 7豁免
					'UserID' =>  $UserID,//订单号吗
					'AppID' =>  $LoanStatus['ID'],//订单号吗
					'OrderAmount' => $LoanStatus['zhanqifei'],//订单号吗
					'TradeNo' =>  $data['inner_trade_no'], //流水
					];
					$loans_paylist_re = Db::table('xb_loans_paylist') -> insertGetId($loans_paylist);
					Db::commit();
					echo 'success';
//					发送短信通知
					  $smsTemp = (new SmsTemplate())->getSmsInfo('zhanqi');
	                  $userInfo = db('loans_applylist')->alias('a')
	                  ->where('a.ID',$LoanStatus['ID'])
	                  ->join('xb_mem_info m','a.UserID = m.ID')
	                  ->find();
	                  $bankInfo = db('renzen_bank')->where(['UserID' => $UserID])->find();
	                  $smsTempStr = str_replace(['#name#','#time#',],[$userInfo['TrueName'],$userInfo['YyFkTime']],$smsTemp['Content']);
//                    发送短信
		              $result1 = (new CLApi())->sendSMS($userInfo['Mobile'],$smsTempStr);
		              $result2 = json_decode($result1,true);
		              if($result2['code'] != 0){
		                  \Think\Log::record('展期操作 发送短信失败 数据 - '.$result1);
		              }
						//写入对接产品记录表
	                   $re=(new Docking())->addDocking(1,($result2['code'] == 0)?2:3,'chuanglan','展期操作发送验证码(主动展期)',$result1);
				} catch (\Exception $e) {
					// 回滚事务
					Db::rollback();
//					p($e->getMessage());die;
				}

			}
		}

	}

	//代付回调通知地址
	public function payment() {
		$data = input();
			    $data_huankuan=json_encode($data,TRUE);
				$fp = fopen('./payment/zhifu.txt',"a+");
				$time=date('Y-m-d H:i:s');
		        fwrite($fp,$time."\n");
				fwrite($fp,$data_huankuan."\n");
		        fclose($fp); 
		$where['OutTradeNo'] = $data['outer_trade_no'];
		$re = Db::table('xb_loans_applylist') -> where($where) -> find();//获取订单数据
		//		判断回调成为的条件
		if ($data['withdrawal_status'] == 'WITHDRAWAL_SUCCESS') {
			$updata['LoanStatus'] = '2';
			$updata['OpenTime'] = date('Y-m-d H:i:s');
		}else{
//		立时代回调放款失败
			$aaa=[
			'order_sn'=>$re['OrderSn'],
			'lending_status'=>'401',
			'fail_reason'=>$data['fail_reason'],
			];
            $songsong=new Songsong();
			$re=$songsong->lendingFeedback($aaa);//放款结果回调接口
			Db::table('xb_loans_applylist') -> where($where) -> update(['lishidai_fangkuan'=>$re]);
		}
		//根据放款订单号  确认放款订单
		if ($re) {
			if($re['OpenTime']){
				echo 'success';
			}else{
				$updata['fail_reason'] = $data['fail_reason'];
				$YyFkTime = strtotime(date('Y-m-d'));
				//预约还款日期转为时间戳
				$days=$re['ApplyDay'];
				$days=$days-1;
				$days=86400*$days;
				$YyFkTime = $YyFkTime + $days;
				$YyFkTime = date("Y-m-d", $YyFkTime);
				$updata['YyFkTime2'] = $YyFkTime;
				//预约还款时间  初始时间不会变
				$updata['YyFkTime'] = $YyFkTime;
				//预约还款时间   续期增加
				$resufl = Db::table('xb_loans_applylist') -> where($where) -> update($updata);
//				p($resufl);die;
				if($resufl){
					       echo 'success';//返回成功终止畅捷回调
		//					立时代回调放款成功
		                    $aaa=[
					'order_sn'=>$re['OrderSn'],
					'lending_status'=>'200',
					'fail_reason'=>$data['fail_reason'],
					];
		            $songsong=new Songsong();
					$re_shenpin=$songsong->lendingFeedback($aaa);//审批结果回调接口
					$re_jihua=$songsong->repayPlanFeedback($re['OrderSn']);//还款计划推送接口
					Db::table('xb_loans_applylist') -> where($where) -> update(['lishidai_fangkuan'=>$re_shenpin]);
					Db::table('xb_loans_applylist') -> where($where) -> update(['lishidai_jihua'=>$re_jihua]);
		//			发送短信
			              $smsTemp = (new SmsTemplate())->getSmsInfo('loan_inform');
			              $userInfo = db('loans_applylist')->alias('a')
			                  ->where($where)
			                  ->join('xb_mem_info m','a.UserID = m.ID')
			                  ->find();
			              $bankInfo = db('renzen_bank')->where(['UserID' => $userInfo['UserID']])->find();
			              $smsTempStr = str_replace(['#name#','#suffix#','#refund_time#'],[$userInfo['TrueName'],substr($bankInfo['BankNo'],-4),$userInfo['YyFkTime']],$smsTemp['Content']);
		//              //发送短信
			              $result1 = (new CLApi())->sendSMS($userInfo['Mobile'],$smsTempStr);
			              $result2 = json_decode($result1,true);
			              if($result2['code'] != 0){
			                  \Think\Log::record('放款操作 发送短信失败 数据 - '.$result1);
			              }
							//写入对接产品记录表
		                   (new Docking())->addDocking(1,($result2['code'] == 0)?2:3,'chuanglan','放款操作验证码',$result1);
			               
			    }
			}
		}
		
	}

	//	根据银行卡号获取银行卡信息
	public function bank_bankNo() {
		$post = $this -> request -> param(true);
		$changpay = new \changpay\ChangPay;
		$datas = $changpay -> bank_datile($post['bankNo']);
		if ($datas['AcceptStatus'] == 'S') {
			show_success($datas);
		} else {
			show_success($datas['OriginalErrorMessage']);
		}
	}

	//	 银行卡手动解绑操作    用户资料误删除
	public function jibang_bank_songsong() {
		$post = $this -> request -> param(true);
		$changpay = new \changpay\ChangPay;
		$MerchantNo = Db::table('xb_sys_inteparameter') -> where('ParaName', 'changpay') -> value('ParaValue');
		//		$MerchantNo = '200002080023' ; //商户号码
		$ressss = $changpay -> jiebang($post['BankNo'], $post['userid'], $MerchantNo);
		p($ressss);
		die ;
		if ($ressss) {
			show_success();
		} else {
			show_error();
		}
	}

}
